<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-card class="box-card">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="dataForm.goodsSn" placeholder="商品编号"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="dataForm.name" placeholder="商品名称"></el-input>
        </el-form-item>
        <el-form-item label="类目" prop="categoryId">
          <template>
            <el-select v-model="dataForm.categoryId" filterable placeholder="请选择">
              <el-option
                v-for="item in category"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <template>
            <el-select v-model="dataForm.brandId" filterable placeholder="请选择">
              <el-option
                v-for="item in brand"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
            <el-form-item label="商品图片" prop="picUrl">
              <el-input v-model="dataForm.picUrl" placeholder="商品图片"></el-input>
            </el-form-item>
            <el-form-item label="详情图片" prop="shareUrl">
              <el-input v-model="dataForm.shareUrl" placeholder="详情图片"></el-input>
            </el-form-item>

        <!--<el-form-item label="轮播图片" prop="gallery">-->
          <!--<el-input v-model="dataForm.gallery" placeholder="轮播图片，采用JSON数组格式"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="关键字" prop="keywords">-->
          <!--<el-input v-model="dataForm.keywords" placeholder="商品关键字，采用逗号间隔"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="商品简介" prop="brief">
          <el-input v-model="dataForm.brief" placeholder="商品简介"></el-input>
        </el-form-item>
        <!--<el-form-item label="商品单位" prop="unit">-->
          <!--<el-input v-model="dataForm.unit" placeholder="商品单位，例如件、盒"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="展示价格" prop="displayPrice">
          <el-input v-model="dataForm.displayPrice" placeholder="展示价格，只用于显示，可填任意格式"></el-input>
        </el-form-item>
        <!--<el-form-item label="销售价格" prop="sellPrice">-->
          <!--<el-input v-model="dataForm.sellPrice" placeholder="销售价格"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="排序字段" prop="sortOrder">
          <el-input-number v-model="dataForm.sortOrder" :min="0" placeholder="排序字段"></el-input-number>
        </el-form-item>
        <el-form-item label="单次上限" prop="limitOnce">
          <el-input-number v-model="dataForm.limitOnce" :min="0" placeholder="单次购买上限（填0为不限）"></el-input-number>
        </el-form-item>
        <el-form-item label="上架" prop="isOnSale">
          <el-radio-group v-model="dataForm.isOnSale">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品详请" prop="detail">
          <script :id="ueId" class="ueditor-box" type="text/plain" style="width: 100%; height: 260px;"></script><img/>
        </el-form-item>

      </el-form>
    </el-card>
    <el-card class="box-card">
      <h3>限购政策</h3>
      <el-table :data="limitTime">
        <el-table-column property="limitTime" width="250" label="限购周期">
          <template slot-scope="scope">
            <el-select v-model="scope.row.time" placeholder="请选择">
              <el-option
                v-for="item in timeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column property="code" width="180" label="限购数量">
          <template slot-scope="scope">
            <el-input-number placeholder="限购数量" v-model="scope.row.count" :min="1" style="width: 120px"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column property="number" width="250" label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="deleteLimit(scope.$index)">删除</el-button><el-button type="primary" @click="addLimit">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card">
      <h3>输入校验</h3>
      <el-table :data="tips">
        <el-table-column property="code" width="180" label="提示">
          <template slot-scope="scope">
            <el-input placeholder="提示" v-model="scope.row.text" style="width: 120px"></el-input>
          </template>
        </el-table-column>
        <el-table-column property="price" width="250" label="校验规则">
          <template slot-scope="scope">
            <el-select v-model="scope.row.regular" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column property="number" width="80" label="是否必选">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.necessary"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column property="number" width="250" label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.$index >= 1" type="danger" @click="deleteTip(scope.$index)">删除</el-button><el-button type="primary" @click="addTip">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card v-if="!dataForm.id" class="box-card">
      <h3>商品规格</h3>
      <el-row v-if="multipleSpec" :span="24" style="padding:20px 0;">
        <el-col :span="3">
          规格一：
        </el-col>
        <el-col :span="6">
            <el-select v-model="good.specificationOne" filterable placeholder="请选择规格类型" @change="specificationOneChange">
              <el-option
                v-for="item in specificationEntities"
                :key="item.id"
                :label="item.specificationName"
                :value="item.id"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="15">
            <el-select v-model="good.specificationOneItemsSelected" multiple filterable placeholder="请选择规格值" @change="specificationSelectedChange" @clear="setDisabled" style="width: 90%;margin-left:10px;">
              <el-option
                v-for="item in good.specificationOneItems"
                :key="item.id"
                :label="item.value"
                :value="item.value"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </el-col>
      </el-row>

      <el-row :span="24" style="padding:20px 0;">
        <el-col :span="3">
          规格二：
        </el-col>
        <el-col :span="6">
          <el-select v-model="good.specificationTwo" filterable clearable placeholder="请选择规格类型" @change="specificationTwoChange">
            <el-option
              v-for="item in specificationEntities"
              :key="item.id"
              :label="item.specificationName"
              :value="item.id"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="15">
          <el-select v-model="good.specificationTwoItemsSelected" multiple filterable placeholder="请选择规格值" @change="specificationSelectedChange" style="width: 90%;margin-left:10px;">
            <el-option
              v-for="item in good.specificationTwoItems"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <!--<el-col :span="3" >-->
          <!--<el-button  type="primary" icon="el-icon-plus"></el-button>-->
        <!--</el-col>-->
      </el-row>

      <el-row :span="24" style="padding:20px 0;">
        <el-col :span="3">
          规格三：
        </el-col>
        <el-col :span="6">
          <el-select v-model="good.specificationThree" filterable clearable placeholder="请选择规格类型" @change="specificationThreeChange">
            <el-option
              v-for="item in specificationEntities"
              :key="item.id"
              :label="item.specificationName"
              :value="item.id"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="15">
          <el-select v-model="good.specificationThreeItemsSelected" multiple filterable placeholder="请选择规格值" @change="specificationSelectedChange" style="width: 90%;margin-left:10px;">
            <el-option
              v-for="item in good.specificationThreeItems"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>

    </el-card>

    <el-card class="box-card">
      <h3>商品库存</h3>
      <el-table :data="products">
        <el-table-column property="value" label="货品规格">
          <template slot-scope="scope">
            <el-tag v-for="tag in scope.row.specifications" :key="tag">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="code" width="200" label="货品编号">
          <template slot-scope="scope">
            <el-input v-model="scope.row.code"  placeholder="sku_no"/>
          </template>
        </el-table-column>
        <el-table-column property="price" width="100" label="货品售价">
          <template slot-scope="scope">
          <el-input v-model="scope.row.price"  placeholder="售价"/>
          </template>
        </el-table-column>
        <el-table-column property="number" width="150" label="货品数量">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.number" size="mini" :min="0" :max="999999" label="数量"></el-input-number>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
  </el-dialog>
</template>

<style>
  .el-card {
    margin-bottom: 10px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .simple-img-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 178px;
    width: 178px;

  }
  .simple-img-uploader :hover {
    border-color: #409EFF;
  }
  .simple-img-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .simple-pic {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import ueditor from 'ueditor'
  export default {

    data () {
      return {
        url: '',
        visible: false,
        ue: null,
        ueId: `J_ueditorBox_product`,
        specForm: { specification: '', value: '', picUrl: '' },
        options: [{
          value: '1',
          label: 'QQ号'
        }, {
          value: '2',
          label: '手机号'
        }, {
          value: '3',
          label: '邮箱'
        }, {
          value: '4',
          label: '数字格式'
        }, {
          value: '5',
          label: '文本格式'
        }],
        timeOptions: [{
          value: '1',
          label: '日'
        }, {
          value: '2',
          label: '周'
        }, {
          value: '3',
          label: '月'
        }],
        tips:[{text:'',regular:'', necessary:false}],
        limitTime:[{time:'',count:1}],
        products: [],
        multipleSpec: true,
        specifications: [],
        good: {
          specificationOne: '',
          specificationTwo: '',
          specificationThree: '',
          specificationOneItems: [],
          specificationOneItemsSelected: [],
          specificationTwoItems: [],
          specificationTwoItemsSelected: [],
          specificationThreeItems: [],
          specificationThreeItemsSelected: []
        },
        specificationEntities: [],
        dataForm: {
          id: 0,
          goodsSn: '',
          name: '',
          categoryId: '',
          categoryName: '',
          brandId: '',
          brandName: '',
          gallery: '',
          keywords: '',
          brief: '',
          isOnSale: '',
          sortOrder: '',
          picUrl: '',
          shareUrl: '',
          unit: '',
          tips: '',
          displayPrice: '',
          sellPrice: '',
          detail: '',
          addTime: '',
          updateTime: '',
          deleted: ''
        },
        category: [],
        brand: [],
        dataRule: {
          goodsSn: [
            { required: true, message: '商品编号不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' }
          ],
          categoryId: [
            { required: true, message: '所属类目不能为空', trigger: 'blur' }
          ],
          // brandId: [
          //   { required: true, message: '所属品牌不能为空', trigger: 'blur' }
          // ],
          // gallery: [
          //   { required: true, message: '轮播图片不能为空', trigger: 'blur' }
          // ],
          tips: [
            { required: true, message: '充值提示不能为空', trigger: 'blur' }
          ],
          isOnSale: [
            { required: true, message: '是否上架不能为空', trigger: 'blur' }
          ]
          // picUrl: [
          //   { required: true, message: '商品页面商品图片不能为空', trigger: 'blur' }
          // ],
          // unit: [
          //   { required: true, message: '商品单位不能为空，例如件、盒', trigger: 'blur' }
          // ]
        }
      }
    },
    methods: {
      init (id) {
        this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.$http({
            url: this.$http.adornUrl(`/product/progoods/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.specificationEntities = data.specificationEntities
              this.category = data.category
              this.brand = data.brand
              this.products = []
              this.tips = [{text:'',regular:'', necessary:false}]
              this.good = {
                specificationOne: '',
                specificationTwo: '',
                specificationThree: '',
                specificationOneItems: [],
                specificationOneItemsSelected: [],
                specificationTwoItems: [],
                specificationTwoItemsSelected: [],
                specificationThreeItems: [],
                specificationThreeItemsSelected: []
              }
              if (this.dataForm.id) {
                this.dataForm.goodsSn = data.progoods.goodsSn
                this.dataForm.name = data.progoods.name
                this.dataForm.categoryId = data.progoods.categoryId
                this.dataForm.categoryName = data.progoods.categoryName
                this.dataForm.brandId = data.progoods.brandId
                this.dataForm.brandName = data.progoods.brandName
                this.dataForm.gallery = data.progoods.gallery
                this.dataForm.keywords = data.progoods.keywords
                this.dataForm.brief = data.progoods.brief
                this.dataForm.isOnSale = data.progoods.isOnSale
                this.dataForm.sortOrder = data.progoods.sortOrder
                this.dataForm.picUrl = data.progoods.picUrl
                this.dataForm.shareUrl = data.progoods.shareUrl
                this.dataForm.unit = data.progoods.unit
                this.dataForm.displayPrice = data.progoods.displayPrice
                this.dataForm.sellPrice = data.progoods.sellPrice
                this.dataForm.detail = data.progoods.detail
                this.dataForm.addTime = data.progoods.addTime
                this.dataForm.updateTime = data.progoods.updateTime
                this.dataForm.deleted = data.progoods.deleted
                this.dataForm.limitOnce = data.progoods.limitOnce
                if (data.progoods.specificationInfo) {
                  this.good = JSON.parse(data.progoods.specificationInfo)
                }
                if (data.progoods.tips != '[]' && data.progoods.tips != null) {
                  this.tips = JSON.parse(data.progoods.tips)
                }
                if (data.progoods.limitTime != '[]' && data.progoods.limitTime != null) {
                  this.limitTime = JSON.parse(data.progoods.limitTime)
                }
                this.products = data.progoods.products
              }

              this.ue = ueditor.getEditor(this.ueId, {
                // serverUrl: this.url, // 服务器统一请求接口路径
                zIndex: 3000
              })
              this.ue.ready(() => {
                this.ue.setContent(this.dataForm.detail)
              })
              this.setDisabled()
            }
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.ue.ready(() => {
              this.dataForm.detail = this.ue.getContent()
            })
            for(var i = 0;this.dataForm.tips.length < i;i ++ ){
              if(this.dataForm.tips[i].text === ''){
                this.$message.error('请填写输入提示')
                return
              }
            }
            this.$http({
              url: this.$http.adornUrl(`/product/progoods/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'goodsSn': this.dataForm.goodsSn,
                'name': this.dataForm.name,
                'categoryId': this.dataForm.categoryId,
                'categoryName': this.dataForm.categoryName,
                'brandId': this.dataForm.brandId,
                'brandName': this.dataForm.brandName,
                'gallery': this.dataForm.gallery,
                'keywords': this.dataForm.keywords,
                'brief': this.dataForm.brief,
                'isOnSale': this.dataForm.isOnSale,
                'sortOrder': this.dataForm.sortOrder,
                'picUrl': this.dataForm.picUrl,
                'shareUrl': this.dataForm.shareUrl,
                'unit': this.dataForm.unit,
                'tips': JSON.stringify(this.tips),
                'limitTime': JSON.stringify(this.limitTime),
                'displayPrice': this.dataForm.displayPrice,
                'sellPrice': this.dataForm.sellPrice,
                'detail': this.dataForm.detail,
                'addTime': this.dataForm.addTime,
                'updateTime': this.dataForm.updateTime,
                'deleted': this.dataForm.deleted,
                'products': this.products,
                'limitOnce': this.dataForm.limitOnce,
                'specificationInfo': JSON.stringify(this.good)
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      specChanged (label) {
        // if (label === false) {
        //   this.good.specifications = [{specification: '规格', value: '标准', picUrl: ''}]
        //   this.products = [{id: 0, specifications: ['标准'], price: 0.00, number: 0, url: ''}]
        // } else {
        //   this.good.specifications = []
        //   this.products = []
        // }
      },
      // 上传之前
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        this.num++
      },
      handlePicSuccess (response, file, fileList) {
        this.dataForm.picUrl = response.url
      },
      handleSharePicSuccess (response, file, fileList) {
        this.dataForm.shareUrl = response.url
      },
      handleError (response, file, fileList) {
        if (JSON.parse(response.message).code === 500) {
          this.$message.error(JSON.parse(response.message).msg)
        } else {
          this.$message.error(response.message)
        }
      },
      specificationOneChange () {
        if (this.good.specificationOne === '') {
          return
        }
        this.setDisabled()
        this.$http({
          url: this.$http.adornUrl(`/product/prospecification/findItem?id=` + this.good.specificationOne),
          method: 'post'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.good.specificationOneItems = data.valueTags
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      specificationTwoChange () {
        if (this.good.specificationTwo === '') {
          return
        }
        this.setDisabled()
        this.$http({
          url: this.$http.adornUrl(`/product/prospecification/findItem?id=` + this.good.specificationTwo),
          method: 'post'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.good.specificationTwoItems = data.valueTags
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      specificationThreeChange () {
        if (this.good.specificationThree === '') {
          return
        }
        this.setDisabled()
        this.$http({
          url: this.$http.adornUrl(`/product/prospecification/findItem?id=` + this.good.specificationThree),
          method: 'post'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.good.specificationThreeItems = data.valueTags
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      setDisabled () {
        for (let i = 0; i < this.specificationEntities.length; i++) {
          if (this.specificationEntities[i].id === this.good.specificationOne ||
              this.specificationEntities[i].id === this.good.specificationTwo ||
              this.specificationEntities[i].id === this.good.specificationThree) {
            this.specificationEntities[i].disabled = true
          } else {
            this.specificationEntities[i].disabled = false
          }
        }
      },
      specificationSelectedChange () {
        let temp = []
        for (let i = 0; i < this.good.specificationOneItemsSelected.length; i++) {
          let product = {id: 0, specifications: [], price: 0.00, number: 0, url: ''}
          product.specifications.push(this.good.specificationOneItemsSelected[i])
          temp.push(product)
        }
        this.products = temp

        if (this.good.specificationTwoItemsSelected.length === 0) {
          return
        }
        temp = []
        for (let i = 0; i < this.products.length; i++) {
          let tempProduct = {id: 0, specifications: [], price: 0.00, number: 0, url: ''}
          this.pushAll(tempProduct.specifications, this.products[i].specifications)

          for (let j = 0; j < this.good.specificationTwoItemsSelected.length; j++) {
            let subProduct = {id: 0, specifications: [], price: 0.00, number: 0, url: ''}
            this.pushAll(subProduct.specifications, tempProduct.specifications)
            subProduct.specifications.push(this.good.specificationTwoItemsSelected[j])
            temp.push(subProduct)
          }
        }
        this.products = temp

        if (this.good.specificationThreeItemsSelected.length === 0) {
          return
        }
        temp = []
        for (let i = 0; i < this.products.length; i++) {
          let tempProduct = {id: 0, specifications: [], price: 0.00, number: 0, url: ''}
          this.pushAll(tempProduct.specifications, this.products[i].specifications)

          for (let j = 0; j < this.good.specificationThreeItemsSelected.length; j++) {
            let subProduct = {id: 0, specifications: [], price: 0.00, number: 0, url: ''}
            this.pushAll(subProduct.specifications, tempProduct.specifications)
            subProduct.specifications.push(this.good.specificationThreeItemsSelected[j])
            temp.push(subProduct)
          }
        }
        this.products = temp
      },
      pushAll (from, tag) {
        for (let j = 0; j < tag.length; j++) {
          from.push(tag[j])
        }
        return from
      },
      deleteTip(index){
        this.tips.splice(index,1)
      },
      addTip(){
        if(this.tips.length >= 3){
          this.$message.error('最多支持3个输入字段')
          return
        }
        this.tips.push({text:'',regular:'', necessary:false})
      },
      deleteLimit(index){
        this.limitTime.splice(index,1)
      },
      addLimit(){
        if(this.limitTime.length >= 3){
          this.$message.error('最多支持3限购规则')
          return
        }
        this.limitTime.push({time:'',count:1})
      }
    }
  }
</script>
